var texts = new Array();
var x = 0;
var y = 0;
var maxx = 0;
var maxy = 0;
window.onload=function(){

	//var theform = document.getElementsByName("form1")[0];
	var inputs = $(".mggb");
	for(var i = 0; i < inputs.length; i++){
	//if(inputs[i].type == "text" || inputs[i].type == "button"){
	texts.push(inputs[i]);
	//}
	}

	for(var i = 0; i < texts.length; i++){
	texts[i].onfocus = new Function("setCurrent('" + texts[i].getAttribute("location") + "')");
	var crtx = parseInt(texts[i].getAttribute("location").split(",")[0]);
	var crty = parseInt(texts[i].getAttribute("location").split(",")[1]);
	maxx = maxx < crtx ? crtx : maxx;
	maxy = maxy < crty ? crty : maxy;
		texts[i].onkeydown = function(e){
		e = e || window.event;
			switch(e.keyCode){
			case 38:movePosition(--x,y,38,1);break;// 上
			case 40:movePosition(++x,y,40,2);break;// 下
			case 37:movePosition(x,--y,37,3);break;// 左
			case 39:movePosition(x,++y,39,4);break;// 右
			default:return true;
			}
		};
	}
};

function movePosition(x1,y1,keyCode,flag){
	x1 = x1 > maxx ? 1 : x1;
	y1 = y1 > maxy ? 1 : y1;
	x1 = x1 < 1 ? maxx : x1;
	y1 = y1 < 1 ? maxy : y1;
	
	if((flag=="2" && x1=="2")||(flag=="2" && x1=="3")||(flag=="2" && x1=="4")){
		y1="1";
	}
	if((flag=="1" && x1=="1")||(flag=="1" && x1=="2")||(flag=="1" && x1=="3")){
		y1="1";
	}
	
	var j = 0;
	for(; j < texts.length; j++){
			if(texts[j].getAttribute("location") == x1 + "," + y1){
				texts[j].focus();
				break;
			}
	}

	if(j == texts.length){
		switch(keyCode){
		case 38:movePosition(--x1,y1,keyCode);break;// 上
		case 40:movePosition(++x1,y1,keyCode);break;// 下
		case 37:movePosition(x1,--y1,keyCode);break;// 左
		case 39:movePosition(x1,++y1,keyCode);break;// 右
		}
	}
}

function setCurrent(location){
	x = location.split(",")[0];
	y = location.split(",")[1];
}
